using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using AspNetCoreTest.Common;
using AspNetCoreTest.HttpServices;
using AspNetCoreTest.Services;
using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ProductManagement.Framework.RabbitMQ;
using ProductManagement.Framework.Serialize.Json;
using Refit;
using RefitService;

namespace AspNetCoreTest
{
    public class Startup
    {
        public Startup(IWebHostEnvironment env)
        {
            IConfigurationBuilder builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true)
            ;
            Configuration = builder.Build();
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            //RabbitMQ
            services.AddProductManagementRabbitMQ(option =>
            {
                var config = Configuration.GetSection("rabbitMQSetting").Get<RabbitMQOption>();
                option.AmqpUris = config.AmqpUris;
                option.Uri = config.Uri;
                option.ExtName = config.ExtName;
            }, new ProductManagement.Framework.Serialize.Json.NewtonsoftSerializer())
            .ScanMessage(typeof(iSchool.RabbitMQ.Handle.SyncBaseHandle).Assembly, this.GetType().Assembly);


            services.AddTransient<IClientErrorFactory, ClientErrorFactory>();
            services.AddControllers().ConfigureApiBehaviorOptions(op =>
            {
                op.InvalidModelStateResponseFactory = context => new BadRequestResult();
            }).AddXmlSerializerFormatters();

            //services.AddHttpClient("user", client =>
            //    client.BaseAddress = new Uri("http://10.1.0.16:9009")
            //).AddTypedClient(c => Refit.RestService.For<IUserHttpService>(c));

            services.AddRefitClient<IUserHttpService>()
                  .ConfigureHttpClient(client =>
                    client.BaseAddress = new Uri("http://10.1.0.16:9009")
                  );


            services.AddHttpClient();

            services.AddScoped<TestNullHttpService>();

            services.AddHttpClient<ITestInjectHttpService, TestInjectHttpService>(option => {
                option.BaseAddress = new Uri("https://m3.sxkid.com");
            });

            services.AddScoped<RoleService>();
            //services.AddScoped<UserService<UserChildService>>();
            //services.AddScoped<UserService<UserChildService>, UserChildService>();


            services.AddCors(options =>
            {
                options.AddPolicy("Cors", configurePolicy =>
                {
                    configurePolicy
                    .SetIsOriginAllowed(isOriginAllowed => true)
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    //.AllowAnyOrigin()
                    .WithOrigins("http://localhost:8001", "http://localhost:8002")
                    ;
                });
            });
        }

        public void ConfigureContainer(ContainerBuilder builder)
        {
            builder.RegisterType<UserChildService>();

            var assemblies = Assembly.Load("iSchool.RabbitMQ.Handle");
            builder.RegisterAssemblyTypes(assemblies).AsImplementedInterfaces();
            //var user = (UserService<UserChildService>)child;
            //builder.RegisterInstance(user);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.SubscribeRabbitMQ();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors("Cors");
            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
